#include <stdio.h>
#include <stdlib.h>
#include "list.h"


//判断列表是否为空
static bool listIsEmpty(List *plist)
{
	if((*plist)->next == NULL){
		return true;
	}


	return false;

}


//判断列表是否为满
bool listIsFull(List *plist)
{
	Node *temp = malloc(sizeof(Node));
	if(temp){
		free(temp);

		return false;
	}

	return true;

}

//返回列表个数
int listCount(List *plist)
{
	int count = 0;
	Node *cur = *plist;//head -- Node *

	cur = cur->next;

	while(cur != NULL){
		count++;
		cur = cur->next;
	}

	return count;
}

//添加项目
bool listAddItem(List *plist, Item item)
{
	Node *cur = (*plist)->next;//head -- Node *
	//Node **head = &(*plist)->next;
	Node *data = NULL;

	data = calloc(1, sizeof(Node));
	if(data == NULL){
		printf("列表已满\n");
		return false;
	}

	data->item = item;

	if(cur == NULL){
		//cur = data;
		(*plist)->next = data;
		//*head = data;
	}else{
		while(cur->next != NULL){
			cur = cur->next;
		}

		cur->next = data;
		data->prev = cur;
	}

	return true;
}

void printItem(Item *item)
{
	printf("title:%s, rating:%d\n", item->title, item->rating);
}

//遍历列表
void listTraverse(List *plist, void (*func)(Item *item))
{
	Node *cur = (*plist)->next;//head -- Node *

	if(listIsEmpty(plist)){
		return;
	}


	while(cur != NULL){
		//代码需要修改兼容不同数据item
		func(&cur->item);
		cur = cur->next;
	}
	
}

//逆序显示列表
void listReverse(List *plist, void (*func)(Item *item))
{
	Node *cur = (*plist)->next;//head -- Node *

	if(listIsEmpty(plist)){
		return;
	}

	while(cur->next != NULL){
		cur = cur->next;
	}

	while(cur != NULL){
		//代码需要修改兼容不同数据item
		func(&cur->item);
		cur = cur->prev;
	}
}

//清空列表
void listEmpty(List *plist)
{

	Node *cur = (*plist)->next;//head -- Node *
	Node *temp = NULL;

	while(cur != NULL){
		temp = cur;
		cur = cur->next;

		free(temp);
	}
	*plist = NULL;

}


//把列表初始化为空的列表
int listInit(List *plist)
{
	Node *node = *plist;

	node->next = NULL;
	node->prev = NULL;

	node->addItem = listAddItem;
	node->count = listCount;
	node->empty = listEmpty;
	node->isEmpty = listIsEmpty;
	node->isFull = listIsFull;
	node->reverse = listReverse;
	node->traverse = listTraverse;
}